
# third party
import socket
import struct
import random
import Queue
import time
from threading import Thread
from threading import Event
from threading import Lock



# first party
from misc import threadPrint



class Throttle:
	def __init__ (self):
		self.alive = True
		self.lock = Lock()

		self.increment = 16 * 1024
		self.bandwidth = 150 * 1024
		self.remaining = 0

		self.gotBandwidth = Event()
		self.limitReseter = Thread(target=self.resetLimiter)
		self.limitReseter.start()

	def resetLimiter (self):
		while self.alive:
			with self.lock:
				self.remaining = self.bandwidth
				self.gotBandwidth.set()
			time.sleep(1)
		threadPrint( "done Throttle Thread" )

	def getBandwidth (self, request = -1):
		with self.lock:
			if not self.alive:
				return 0
		
		self.gotBandwidth.wait()
		
		with self.lock:
			if request < 0:
				request = self.increment		
				
			ration = min(request, self.increment, self.remaining)
			self.remaining -= ration
			if self.remaining <= 0:
				self.gotBandwidth.clear()
			return ration
				

	def kill (self):
		with self.lock:
			self.alive = False




